import React, { useEffect } from 'react';
import { connect } from 'umi';
import { Form, Button, Upload, message, Row, Col, Card } from 'antd';
import FormCondition from '@/components/FormCondition';
import { UploadOutlined } from "@ant-design/icons";
import * as XLSX from "xlsx";

import DrawerCondition from '@/components/DrawerCondition';

const editWhite = (props) => {
  const { dispatch, visible = {}, onClose, handleCallback, loading } = props;

  const { show = false, detail = {} } = visible;
  const { id } = detail;
  const [form] = Form.useForm();
  // 新增修改 传id修改 不传id新增
  const fetchRoleEdit = () => {
    form.validateFields().then((values) => {
      const { filterWordList } = values;
      const payload = {
        goodsId: id,
        mobileList:
          filterWordList
            .replace(/(\r\n)|\r|\n/g, '\n')
            .split(/\n+/g)
            .filter((item) => {
              if (item) {
                return true;
              } else {
                return false;
              }
            }),
      };
      dispatch({
        type: 'liveStreaming/fakeSaveGoodsWhitelist',
        payload: payload,
        callback: () => {
          onClose();
          handleCallback();
        },
      });
    });
  };
  const handleUpload = (file) => {
    const fileType = file.type;
    const allowedTypes = ["application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"];
    if (!allowedTypes.includes(fileType)) {
      message.error("只能上传Excel文件！");
      return false;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: "array" });
      const worksheet = workbook.Sheets[workbook.SheetNames[0]];
      const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
      form.setFieldsValue({
        filterWordList: form.getFieldValue('filterWordList') ? form.getFieldValue('filterWordList') : '' + jsonData.filter((item, index) => {
          return index !== 0
        }).join('\n')
      })
    };
    reader.readAsArrayBuffer(file);

    return false; // 阻止默认上传行为
  };
  const formItems = [
    {
      label: '白名单',
      name: 'filterWordList',
      placeholder: '请输入手机号，支持批量添加,换行隔开',
      type: 'textArea',
    },
  ];

  const modalProps = {
    title: `${id ? '修改' : '新增'}`,
    visible: show,
    onClose,
    footer: (
      <Button type="primary" loading={loading} onClick={fetchRoleEdit}>
        确定
      </Button>
    ),
  };

  return (
    <DrawerCondition {...modalProps}>
      <FormCondition form={form} formItems={formItems} initialValues={detail}></FormCondition>
      <Row gutter={[16, 16]}>
        <Col span={6} ></Col>
        <Col span={16}>
          <Upload beforeUpload={handleUpload}>
            <Button icon={<UploadOutlined />}>解析Excel文件</Button>
          </Upload>
          <Button type="link">
            <a href="https://wx.gy.cn/template/mobileWhite.xlsx">下载模板</a>
          </Button>
        </Col>
      </Row>
    </DrawerCondition>
  );
};

export default connect(({ information, loading }) => ({
  loading: loading.models.liveStreaming,
}))(editWhite);
